package com.ktgj.customer.task;

import cn.hutool.bloomfilter.filter.SDBMFilter;
import cn.hutool.core.date.DateUtil;
import com.ktgj.common.core.annotation.Excel;
import com.ktgj.common.core.constant.*;
import com.ktgj.common.core.utils.DateCalcUtils;
import com.ktgj.common.core.utils.DateUtils;
import com.ktgj.customer.common.HanglianUtils;
import com.ktgj.customer.domain.*;
import com.ktgj.customer.domain.vo.ProductVo;
import com.ktgj.customer.mapper.*;
import com.ktgj.customer.service.IInsuranceRecordService;
import com.ktgj.customer.service.ICardPurchaseService;
import com.ktgj.flight.api.RemoteFlightService;
import com.ktgj.flight.api.domain.FlightOrderDetailsList;
import com.ktgj.flight.api.domain.FlightOrderInfo;
import com.ktgj.flight.api.domain.FlightOrderList;
import com.ktgj.hotel.api.RemoteHotelService;
import com.ktgj.hotel.api.domain.HotelOrder;
import com.ktgj.train.api.RemoteTrainService;
import com.ktgj.train.api.domain.TrainOrder;
import org.apache.ibatis.ognl.OgnlRuntime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;


@Component
public class Scheduler {

    @Autowired
    private BusinessOrderMapper businessOrderMapper;
    @Autowired
    private CustomerRightdetailMapper customerRightdetailMapper;
    @Autowired
    private OrderInfoMapper orderInfoMapper;
    @Autowired
    private MallOrderMapper mallOrderMapper;
    @Autowired
    private ICardPurchaseService cardPurchaseService;
    @Autowired
    private InsuranceRecordMapper insuranceRecordMapper;
    @Autowired
    private GuaranteeMapper guaranteeMapper;
    @Autowired
    private IInsuranceRecordService insuranceRecordService;
    @Autowired
    private TravelContractMapper travelContractMapper;
    @Autowired
    private CustomerCardMapper customerCardMapper;
    @Autowired
    private CustomerMapper customerMapper;
    @Autowired
    private TravelGroupMapper travelGroupMapper;
    @Autowired
    private TravelGroupNumberMapper travelGroupNumberMapper;
    @Autowired
    private EmployeeThingMapper employeeThingMapper;
    @Autowired
    private RemoteFlightService remoteFlightService;
    @Autowired
    private RemoteHotelService remoteHotelService;
    @Autowired
    private RemoteTrainService remoteTrainService;
    @Autowired
    private DdCouponAuditMapper ddCouponAuditMapper;
    @Autowired
    private CouponMapper couponMapper;
    @Autowired
    private DdCouponAddMapper ddCouponAddMapper;

    /**
     * 取消订单
     */
    @Scheduled(fixedDelay = 1000 * 60)
    public void cancelOrder() {
        List<BusinessOrder> businessOrders = businessOrderMapper.selectbusinessorderByState();
        for (BusinessOrder item : businessOrders) {
            item.setState(CustomerConstants.cancelPay.getValue());
            item.setOrderState(CustomerConstants.cancelPay.getValue());
            businessOrderMapper.updateBusinessOrder(item);
            CustomerRightdetail rightdetail = new CustomerRightdetail();
            rightdetail.setCustomerRightdetailId(item.getUsedCouponId());
            rightdetail.setRightdetailState(CustomerConstants.unexecuted.getValue());
            customerRightdetailMapper.updateCustomerRightdetail(rightdetail);
        }
    }

    @Scheduled(cron = "0 0 1 * * ?")
//    @Scheduled(fixedDelay = 1000 * 60)
    public void ddCouponAudit()
    {
        DdCouponAudit ddCouponAudit = new DdCouponAudit();
        ddCouponAudit.setState("2");
        List<DdCouponAudit> lstCouponAudit = ddCouponAuditMapper.selectDdCouponAuditList(ddCouponAudit);
        Coupon coupon = new Coupon();
        List<Coupon> lstCoupon = couponMapper.selectCouponList(coupon);
        for (DdCouponAudit tmpDDCouponAudit : lstCouponAudit)
        {
            Customer customer = customerMapper.selectCustomerById(tmpDDCouponAudit.getCustomerId());
            if (customer != null)
            {
                CustomerRightdetail tmpCustomerRightdetail = new CustomerRightdetail();
                Coupon ddCoupon = lstCoupon.stream().filter(item -> item.getCouponType().equals(CustomerConstants.CouponTypeDD.getValue())).findFirst().orElse(null);
                if (ddCoupon != null)
                {
                    tmpCustomerRightdetail.setCouponMoney(new BigDecimal(30));
                    tmpCustomerRightdetail.setCreateEmployeeId(Constant.ADMIN_ID);
                    tmpCustomerRightdetail.setInvalidDate(DateCalcUtils.addYear(DateUtils.getNowDate(), 1));
                    tmpCustomerRightdetail.setValidDate(DateUtils.getNowDate());
                    tmpCustomerRightdetail.setCreateTime(DateUtils.getNowDate());
                    tmpCustomerRightdetail.setCustomerId(customer.getCustomerId());
                    tmpCustomerRightdetail.setRightdetailTypeid(ddCoupon.getCouponId());
                    tmpCustomerRightdetail.setRightdetailType(CustomerConstants.rightTypeCoupon.getValue());
                    tmpCustomerRightdetail.setRightdetailSource(CustomerConstants.rightSourceAdd.getValue());
                    tmpCustomerRightdetail.setRightdetailState(CustomerConstants.unexecuted.getValue());
                    tmpCustomerRightdetail.setRightdetailName(ddCoupon.getCouponName());
                    customerRightdetailMapper.insertCustomerRightdetail(tmpCustomerRightdetail);
                    DdCouponAdd ddCouponAdd = new DdCouponAdd();
                    ddCouponAdd.setCouponAmount("30");
                    ddCouponAdd.setCustomerId(customer.getCustomerId());
                    ddCouponAdd.setCustomerName(customer.getCustomerName());
                    ddCouponAdd.setCustomerPhone(customer.getContractPhoneOne());
                    ddCouponAdd.setValidTime(DateUtils.getNowDate());
                    ddCouponAdd.setCreateTime(DateUtils.getNowDate());
                    ddCouponAdd.setInvalidTime(DateCalcUtils.addYear(DateUtils.getNowDate(), 1));
                    ddCouponAdd.setIsexport("false");
                    ddCouponAddMapper.insertDdCouponAdd(ddCouponAdd);
                }
            }
        }
    }

    /**
     * 获取所有VIP经理需要跟进的订单内容
     */

//    @Scheduled(fixedDelay = 1000 * 60)
    @Scheduled(cron = "0 0 1 * * ?")
    public void getOrderThingsList()
    {
        List<FlightOrderList> lstFlightInfo = remoteFlightService.orderListThings();
        List<HotelOrder> lstHotelOrder = remoteHotelService.orderListThings();
        List<TrainOrder> lstTrainOrder = remoteTrainService.orderListThings();
        if (lstFlightInfo.size() > 0)
        {
            for (FlightOrderList flightOrderInfo : lstFlightInfo)
            {
                EmployeeThing tmpEmployeeThing = new EmployeeThing();
                tmpEmployeeThing.setCustomerId(flightOrderInfo.getCustomerId());
                tmpEmployeeThing.setOrderId(Long.valueOf(flightOrderInfo.getOrderId()));
                List<EmployeeThing> lstData = employeeThingMapper.selectEmployeeThingList(tmpEmployeeThing);
                if (lstData.size() == 0)
                {
                    Customer customer = customerMapper.selectCustomerById(flightOrderInfo.getCustomerId());
                    EmployeeThing employeeThing = new EmployeeThing();
                    employeeThing.setBusinessType(BusinessTypeConstants.flight.getValue());
                    employeeThing.setCustomerId(flightOrderInfo.getCustomerId());
                    employeeThing.setCustomerName(customer.getCustomerName());
                    employeeThing.setOrderId(Long.valueOf(flightOrderInfo.getOrderId()));
                    employeeThing.setDepartureCheckin(flightOrderInfo.getOrderDetailsLists().get(0).getDepartureTime());
                    employeeThing.setCreateTime(new Date());
                    employeeThing.setTicketNight(Long.valueOf(flightOrderInfo.getOrderDetailsLists().size()));
                    employeeThingMapper.insertEmployeeThing(employeeThing);
                }
            }
        }
        if (lstHotelOrder.size() > 0)
        {
            for (HotelOrder hotelOrder : lstHotelOrder)
            {
                EmployeeThing tmpEmployeeThing = new EmployeeThing();
                tmpEmployeeThing.setCustomerId(hotelOrder.getCustomerid());
                tmpEmployeeThing.setOrderId(Long.valueOf(hotelOrder.getOrderid()));
                List<EmployeeThing> lstData = employeeThingMapper.selectEmployeeThingList(tmpEmployeeThing);
                if (lstData.size() == 0)
                {
                    Customer customer = customerMapper.selectCustomerById(hotelOrder.getCustomerid());
                    EmployeeThing employeeThing = new EmployeeThing();
                    employeeThing.setBusinessType(BusinessTypeConstants.hotel.getValue());
                    employeeThing.setCustomerId(hotelOrder.getCustomerid());
                    employeeThing.setCustomerName(customer.getCustomerName());
                    employeeThing.setOrderId(Long.valueOf(hotelOrder.getOrderid()));
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                    try
                    {
                        employeeThing.setDepartureCheckin(sdf.parse(hotelOrder.getArrivetime()));
                    } catch (ParseException e)
                    {
                        e.printStackTrace();
                    }
                    employeeThing.setCreateTime(new Date());
                    employeeThing.setTicketNight(Long.valueOf(hotelOrder.getNumberOfRooms()));
                    employeeThingMapper.insertEmployeeThing(employeeThing);
                }
            }
        }
        if (lstTrainOrder.size() > 0)
        {
            for (TrainOrder trainOrder : lstTrainOrder)
            {
                EmployeeThing tmpEmployeeThing = new EmployeeThing();
                tmpEmployeeThing.setCustomerId(trainOrder.getJsjid());
                tmpEmployeeThing.setOrderId(Long.valueOf(trainOrder.getOrderid()));
                List<EmployeeThing> lstData = employeeThingMapper.selectEmployeeThingList(tmpEmployeeThing);
                if (lstData.size() == 0)
                {
                    Customer customer = customerMapper.selectCustomerById(trainOrder.getJsjid());
                    EmployeeThing employeeThing = new EmployeeThing();
                    employeeThing.setBusinessType(BusinessTypeConstants.train.getValue());
                    employeeThing.setCustomerId(trainOrder.getJsjid());
                    employeeThing.setCustomerName(customer.getCustomerName());
                    employeeThing.setOrderId(Long.valueOf(trainOrder.getOrderid()));
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                    try
                    {
                        employeeThing.setDepartureCheckin(sdf.parse(trainOrder.getTraveldate()));
                    } catch (ParseException e)
                    {
                        e.printStackTrace();
                    }
                    employeeThing.setCreateTime(new Date());
                    employeeThing.setTicketNight(0l);
                    employeeThingMapper.insertEmployeeThing(employeeThing);
                }
            }
        }
    }

    @Scheduled(fixedDelay = 1000 * 60)
    public void cancelTravelOrder() {
        List<OrderInfoDto> orderInfoDtoList = orderInfoMapper.selectStatus();
        for (OrderInfoDto orderInfoDto : orderInfoDtoList) {
            orderInfoDto.setPayStatus(CustomerConstants.cancelPay.getValue());
            orderInfoMapper.updateOrderInfo(orderInfoDto);
        }
    }

    /**
     * 商城自动取消订单
     */
    @Scheduled(fixedDelay = 1000 * 60)
    public void cancelMallOrder() {
        List<MallOrder> mallOrders = mallOrderMapper.selectMallOrderByStatus();
        if (mallOrders != null && mallOrders.size() > 0) {
            mallOrders.forEach(item -> {
                item.setStatus(MallStatus.cancelled.getValue());
                mallOrderMapper.updateMallOrder(item);
            });
        }
    }

    /**
     * 卡到期之后的自动开卡
     */
    @Scheduled(cron = "0 0 3 * * ?")
    public void cardInvalid(){
        List<CustomerCard> invalidCards = customerCardMapper.selectCustomerCardByInvalid();//快过期的卡的人员名单
        cardPurchaseService.cardInvalid(invalidCards);
    }

    @Scheduled(cron = "0 0 0 * * ?")
    public void updateCardInvalid(){
        cardPurchaseService.updateCardInvalid();
    }

    /**
     * 航联保险定时开保(每天凌晨一点执行一次)
     * */
    @Scheduled(cron = "0 0 1 * * ?")
    public void hangLianOpenInsurance(){
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        int count = 0;
        int i = 0;
        //获取所有暂缓开通的保险信息
        List<Guarantee> guaranteeList = guaranteeMapper.suspendOpening();
        if (guaranteeList.size() > 0){
            for (Guarantee guarantee : guaranteeList) {
                List<InsuranceRecord> insuranceRecordList = insuranceRecordMapper.selInsuranceRecordList(guarantee.getCustomerId(), guarantee.getInsTypeId(), guarantee.getInsCoId());
                if (insuranceRecordList == null || insuranceRecordList.size() < 2){
                    if (i == 0){
                        count = insuranceRecordList.size();
                        i = 1;
                    }

                    try {
                        ProductVo productVo = new ProductVo();
                        productVo.id = guarantee.getAssistProductId();
                        productVo.orderNum = guarantee.getPayorderid();
                        productVo.orderSource = guarantee.getBusinessSource();
                        productVo.paymentChannel = guarantee.getBankid();

                        Date date = new Date();
                        String time = format.format(date);
                        productVo.insuranceStartDate = time;
                        productVo.cardNum = guarantee.getCustomerCard();
                        boolean b = insuranceRecordService.hangLianOpenInsurance(guarantee.getCustomerId(), productVo);
                        if (b){
                            System.out.println("开通成功");
                        }
                        else {
                            System.out.println("开通失败");
                        }
                        count = count + 1;
                    } catch (Exception e){
                        System.out.println(e.getMessage());
                    }
                }

                if (count == 2){
                    break;
                }
            }
        }
    }

    /**
     * 已过期保险状态修改
     * */
    @Scheduled(cron = "0 */1 * * * ?")
//    @Scheduled(fixedDelay = 1000 * 60)
    public void updateExpiredStart(){
        Date date = new Date();
        //获取开通成功的保险信息
        List<InsuranceRecord> insuranceRecordList = insuranceRecordMapper.expiredStartList();
        if (insuranceRecordList.size() > 0){
            for (InsuranceRecord insuranceRecord : insuranceRecordList) {
                //过期时间大于当前时间
                if (date.getTime()>insuranceRecord.getInsInvalidDate().getTime()){
                    //开保状态 = 已到期
                    insuranceRecord.setOpenState(InsuranceTypeEnum.Maturity.getValue());
                    insuranceRecordMapper.updateInsuranceRecord(insuranceRecord);
                }
            }
        }
    }

    /**
     * 供应商合同状态修改（每天凌晨一点执行一次）
     */
    @Scheduled(cron = "0 0 1 * * ?")
    public void updateContractStart(){
        Date date = new Date();
        List<TravelContract> travelContracts = travelContractMapper.enableContractList(null);
        if (travelContracts != null && travelContracts.size() > 0){
            for (TravelContract travelContract : travelContracts) {
                if (travelContract.getEndTime().compareTo(date) <= 0){
                    travelContractMapper.updateStart(travelContract.getContractId());

                    travelGroupMapper.updateStart(travelContract.getContractId());
                    List<TravelGroup> travelGroups = travelGroupMapper.travelGroupIdList(travelContract.getContractId());
                    if (travelGroups != null &&travelGroups.size() > 0){
                        for (TravelGroup travelGroup : travelGroups) {
                            travelGroupNumberMapper.updateStart(travelGroup.getGroupId());
                        }
                    }
                }
            }
        }
    }
}
